var crypto = require('crypto');
var pool = require('./db').getPool();

function User(user) {
    this.name = user.name;
    this.password = user.password;
    this.email = user.email;
}

module.exports = User;

User.prototype.save = function (callback) {
    var md5 = crypto.createHash('md5');
    var email_MD5 = md5.update(this.email.toLowerCase()).digest('hex');
    var head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48";
    var user = {
       name: this.name,
       password: this.password,
       email: this.email,
       head: head
    };
    pool.acquire(function (err, mongodb) {
        if (err){
           return callback(err);
        }
        mongodb.collection('users', function (err, collection) {
            if(err){
                pool.release(mongodb);
                return callback(err);
            }
            collection.insert(user, {safe: true}, function (err, user) {
                pool.release(mongodb);
                if (err){
                    return callback(err);
                }
                callback(null, user.ops[0]);
            });
        });
    });
};

User.get = function (name, callback) {
    pool.acquire(function (err, mongodb) {
        if(err){
            return callback(err);
        }
        mongodb.collection('users', function (err, collection) {
            if(err){
                pool.release(mongodb);
                return callback(err);
            }
            collection.findOne({
                "name": name
            }, function (err, user) {
                pool.release(mongodb);
                if(err){
                    return callback(err);
                }
                callback(null, user);
            });
        });
    });
};